<template>
	<view class="map-page">
		<!-- <map id="map" :longitude="center.lng" :latitude="center.lat" scale="14" style="width: 100%; height: 100%;" enable-heatmap :heatmap="heatmapData" subkey="NBFBZ-6DNCN-PBVFD-SOOKO-TB2AK-KABRF" layer-style="1" show-location /> -->
		<!-- 底图 min-scale="11" -->
		<map
			id="map"
			:longitude="center.lng"
			:latitude="center.lat"
			scale="14"
			style="width: 100%; height: 100%"
			show-location
		/>

		<!-- 热力图层 -->
		<canvas
			type="2d"
			ref="canvasRef"
			canvas-id="heatmap"
			id="heatmap"
			class="heatmap-canvas"
		></canvas>
	</view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
const canvasRef = ref(null);
const center = ref({
	lng: 117.801679,
	lat: 30.537465
});

// 模拟接口数据
const apiData = [
	{ lng: 117.784965, lat: 30.549013, count: 24 },
	{ lng: 117.802256, lat: 30.538435, count: 60 },
	{ lng: 117.799451, lat: 30.502502, count: 90 }
];

onMounted(async () => {
	await nextTick();
	drawHeatmap(apiData);
});

/**
 * 根据数据点绘制热力图
 */
function drawHeatmap(points) {
	const canvas = canvasRef.value;
	if (!canvas) return;
	const ctx = canvas.getContext('2d');
	const width = res[0].width;
	const height = res[0].height;
	const dpr = uni.getSystemInfoSync().pixelRatio;
	canvas.width = width * dpr;
	canvas.height = height * dpr;
	ctx.scale(dpr, dpr);
	ctx.clearRect(0, 0, width, height);

	// 模拟获取地图可视范围（真实项目可用 mapContext.getRegion）
	const ne = { lng: 117.81, lat: 30.55 }; // 东北角
	const sw = { lng: 117.78, lat: 30.5 }; // 西南角

	data.forEach((p) => {
		const x = ((p.lng - sw.lng) / (ne.lng - sw.lng)) * width;
		const y = ((ne.lat - p.lat) / (ne.lat - sw.lat)) * height;

		const radius = 60;
		const grd = ctx.createRadialGradient(x, y, 0, x, y, radius);
		grd.addColorStop(0, `rgba(255,0,0,${p.count / 100})`);
		grd.addColorStop(0.5, 'rgba(255,165,0,0.4)');
		grd.addColorStop(1, 'rgba(255,255,0,0)');

		ctx.fillStyle = grd;
		ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
	});
}
</script>

<style scoped>
.map-page {
	width: 100%;
	height: 100%;
	position: relative;
}
.heatmap-canvas {
	position: absolute;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	pointer-events: none; /* 不挡住地图拖动缩放 */
	z-index: 99;
}
</style>
